<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
  <script type="module">
    import { h, diff, render, patch, utils } from './dist/magic-dom.js'

    const { set } = utils
    
    class Component {
      vdom = null // 组件的虚拟DOM表示
      $el = null // 虚拟DOM生成的真实节点

      state = {
        props: {
          className: 'box',
          data: 'infomation'
        },
        list: ['a', 'b', 'c', 'd']
      }

      // 手动修改组件state
      setState(newState) {
        this.state = {
          ...this.state,
          ...newState
        }
        const newVdom = this.render()
        const patches = diff(this.vdom, newVdom)
        patches && patch(this.$el, patches)
        this.vdom = newVdom
      }

      changeList(list) {
        this.setState({ list })
      }

      render() {
        const { list, props } = this.state
        return h('div', props, list.map(t => h('p', {key: t}, t)))
      }
    }

    function createElement(app, component) {
      const vdom = component.render()
      component.vdom = vdom
      component.$el = render(vdom) // 将虚拟 DOM 转换为真实 DOM
      app.appendChild(component.$el)
    }

    const app = document.getElementById('app')
    const component = new Component
    createElement(app, component)
       
    const diffs = []

    setTimeout(() => {
      set('diffType', 'cito')
      const list = ['b', 'c', 'd', 'e', 'f', 'g']
        .sort((a, b) => Math.random() * 2 - 1)
      console.log(list)
      component.changeList(list)
    }, 500)
    setTimeout(() => {
      set('diffType', 'snabbdom')
      const list = ['a', 'c', 'd', 'e', 'f', 'g']
        .sort((a, b) => Math.random() * 2 - 1)
      console.log(list)
      component.changeList(list)
    }, 1000)
    setTimeout(() => {
      set('diffType', 'virtual-dom')
      const list = ['a', 'b', 'd', 'e', 'f', 'g']
        .sort((a, b) => Math.random() * 2 - 1)
      console.log(list)
      component.changeList(list)
    }, 1500)
  </script>
</body>
</html>